#include <csignal>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <unistd.h>
#include <vector>

#include <nlohmann/json.hpp>

#include "cutting.hpp"
#include "decode_h264.hpp"
#include "demuxer_rtsp.hpp"
#include "logger.hpp"
#include "ringbuffer.hpp"

/* 程序主动退出标志位 */
volatile bool running = true;

/**
 * @brief 信号处理函数，接收 CTRL+C 退出信号
 */
void signal_handler(int signal)
{
    if (signal == SIGINT) {
        std::cout << std::endl;
        running = false;
    }
}

/**
 * @brief 主函数
 */
int main(int argc, char** argv)
{
    std::vector<cutting*> cuts;
    signal(SIGINT, signal_handler);

    Logger::info("    _    ___ ___ _____  __     ___     ___   ____    ____ _   _ _____ ");
    Logger::info("   / \\  |_ _|_ _|_   _| \\ \\   / / |   / _ \\ / ___|  / ___| | | |_   _|");
    Logger::info("  / _ \\  | | | |  | |    \\ \\ / /| |  | | | | |  _  | |   | | | | | |  ");
    Logger::info(" / ___ \\ | | | |  | |     \\ V / | |__| |_| | |_| | | |___| |_| | | |  ");
    Logger::info("/_/   \\_\\___|___| |_|      \\_/  |_____\\___/ \\____|  \\____|\\___/  |_|  ");
    Logger::info("");

    /* 参数参数校验 */
    if (argc < 2) {
        std::cout << "Usage: " << argv[0] << " config" << std::endl;
        std::cout << "   eg: " << argv[0] << " ./config/aiit.json" << std::endl;
        std::cout << "   eg: " << argv[0] << " ./config/home.json" << std::endl;
        std::cout << std::endl;
        return -1;
    }

    /* 打开摄像头配置文件 */
    std::ifstream file(argv[1]);
    if (!file.is_open()) {
        Logger::error("Could not open the file");
        return 1;
    }

    /* 解析摄像头配置文件 */
    nlohmann::json j;
    file >> j;

    /* 获取 cameras 数组的大小 */
    auto cameras = j["cameras"];
    size_t num_cameras = cameras.size();

    /* 遍历 cameras 数组并提取每个 IP 地址, SA 屏蔽区域 */
    for (size_t i = 0; i < num_cameras; ++i) {
        std::vector<std::vector<int>> regions;

        /* 获取当前相机对象 */
        const auto& camera = cameras[i];

        /* 解析 IP 字段 */
        if (!(camera.find("ip") != camera.end())) {
            Logger::error("invalid ip in camera");
            return -1;
        }

        Logger::info("Camera {}", (std::string)camera["ip"]);

        /* 解析 SA 屏蔽区域 */
        if (camera.find("sa") != camera.end() && camera["sa"].is_array()) {
            for (const auto& region : camera["sa"]) {
                if (region.is_array() && region.size() == 4) {
                    regions.push_back({ region[0].get<int>(),
                        region[1].get<int>(),
                        region[2].get<int>(),
                        region[3].get<int>() });
                } else {
                    Logger::warn("Invalid region format in camera {}", (std::string)camera["ip"]);
                    return -1;
                }
            }

            /* 打印解析到的 JSON 信息 */
            Logger::info("shielded area:");
            for (const auto& region : regions) {
                Logger::info("    [{}, {}, {}, {}]", region[0], region[1], region[2], region[3]);
            }
        }

        /* 创建切片对象 */
        cutting* cut = new cutting(camera["ip"], regions);
        cuts.push_back(cut);
    }

    /* 等待退出信号 */
    while (running) {
        sleep(1);
    }

    /* 主动销毁 cutting 对象，将会调用 cutting 的析构函数 */
    for (cutting* cut : cuts) {
        delete cut;
    }

    /* 清空 vector */
    cuts.clear();

    return 0;
}